/**
 * @Author liangzai
 * @Description:
 */
public class Test {
    public static void mergeSort(int[] array) {
        mergeSortTmp(array,0,array.length-1);
    }

    private static void mergeSortTmp(int[] array,int left,int right) {
        if(left >= right) {
            return;
        }
        int mid = (left + right) / 2;
        mergeSortTmp(array,left,mid);
        mergeSortTmp(array,mid+1,right);
        //走到这里 全部分解完毕
        // 合并
        merge(array,left,mid,right);
    }

    private static void merge(int[] array, int left, int mid, int right) {
        int[] tmp = new int[right-left+1];
        int k = 0;
        int s1 = left;
        //int e1 = mid;
        int s2 = mid+1;
        //int e2 = right;
        while (s1 <= mid && s2 <= right) {
            if(array[s1] <= array[s2]) {
                tmp[k++] = array[s1++];
            }else {
                tmp[k++] = array[s2++];
            }
        }
        while (s1 <= mid) {
            tmp[k++] = array[s1++];
        }
        while (s2 <= right) {
            tmp[k++] = array[s2++];
        }
        //可以保证tmp数组 是有序的
        for (int i = 0; i < k; i++) {
            array[i+left] = tmp[i];
        }
    }

    /**
     * 非递归实现 归并排序
     * @param array
     */
    public static void mergeSortNor(int[] array) {
        int gap = 1;
        while (gap < array.length) {
            for (int i = 0; i < array.length; i = i + gap * 2) {
                int left = i;
                int mid = left + gap - 1;
                if(mid >= array.length) {
                    mid = array.length-1;
                }
                int right = mid + gap;
                if(right >= array.length) {
                    right = array.length-1;
                }
                merge(array,left,mid,right);
            }
            gap *= 2;
        }
    }

    /**
     * 计数排序：
     * 时间复杂度：O(范围 + n )
     *       范围越大  越慢
     * 空间复杂度：O(范围)
     * 稳定性：
     * @param array
     */
    public static void countSort(int[] array) {
        //1. 找最大值 和 最小值 来确定 计数数组的大小
        int maxVal = array[0];
        int minVal = array[0];
        for (int i = 1; i < array.length; i++) {
            if(array[i] < minVal) {
                minVal = array[i];
            }
            if(array[i] > maxVal) {
                maxVal = array[i];
            }
        }
        int len = maxVal - minVal + 1;
        int[] count = new int[len];

        //2. 遍历原来的数组array把 每个元素 放到对应的计数数组当中 进行计数
        for (int i = 0; i < array.length; i++) {
            int index = array[i];
            count[index-minVal]++;
        }
        //3.依次 遍历计数数组 O(范围)
        int index = 0;
        for (int i = 0; i < count.length; i++) {
            while (count[i] != 0) {
                array[index] = i+minVal;
                index++;
                count[i]--;
            }
        }
    }
}
